package com.xgry.bpm.api.base.activiti.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgry.bpm.api.base.createtable.entity.CreateTable;
import com.xgry.bpm.api.base.createtable.service.CreateTableService;
import com.xgry.bpm.api.base.formcontrol.entity.FormControl;
import com.xgry.bpm.api.base.formcontrol.service.FormControlService;
import com.xgry.bpm.api.base.formlist.entity.FormList;
import com.xgry.bpm.api.base.formlist.service.FormListService;
import com.xgry.bpm.api.base.reviewer.service.ReviewerService;
import com.xgry.bpm.api.base.sqldata.service.SqlData;
import com.xgry.bpm.api.base.tableclass.entity.TableClass;
import com.xgry.bpm.api.base.tableclass.service.TableClassService;
import com.xgry.bpm.api.business.leave.entity.Leave;
import com.xgry.bpm.api.business.leave.service.LeaveService;
import com.xgry.bpm.api.base.userInfo.entity.UserInfo;
import com.xgry.bpm.api.base.userInfo.service.UserInfoService;
import com.xgry.bpm.common.enums.SystemEnum;
import com.xgry.bpm.common.utils.DateTimeUtil;
import com.xgry.bpm.common.utils.Result;
import com.xgry.bpm.config.datasouce.oldsource.DataDBServer;
import com.xgry.bpm.config.datasouce.oldsource.MSFactory;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.javax.el.ExpressionFactory;
import org.activiti.engine.impl.javax.el.ValueExpression;
import org.activiti.engine.impl.juel.ExpressionFactoryImpl;
import org.activiti.engine.impl.juel.SimpleContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.DelegationState;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
public class ActivitiTaskController {

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;

    @Autowired
    ProcessEngineFactoryBean processEngine;

    @Autowired
    private TaskService taskService;

    @Autowired
    private FormListService formListService;

    @Autowired
    private SqlData sqlData;

    @Autowired
    private LeaveService leaveService;

    @Autowired
    private DataDBServer dbServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CreateTableService createTableService;

    @Autowired
    private TableClassService tableClassService;

    @Autowired
    private ReviewerService reviewerService;

    @Autowired
    private FormControlService formControlService;

    @RequestMapping(value = "/leavePage.do")
    public Result leavePage(@RequestParam("page")Integer pageIndex , @RequestParam("rows")Integer pageSize , Leave leave) {
        IPage<Leave> leaveIPage = leaveService.selectPage(new Page<>(pageIndex, pageSize), leave);
        return Result.convertIpageToSuccess(leaveIPage);
    }

    /**
     * 提交流程申请
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/startApply.do", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String startApply(String taskId, String formId, HttpSession session) throws Exception {
        JSONObject json = new JSONObject();
        try {
            JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
            int formlistId = Integer.parseInt(formId);
            FormList formList = formListService.getById(formlistId);
            String cTableName = formList.getCTableName();
            //查出表单所有数据
            String sqlAll = "select * from " + cTableName +" where "+cTableName+"_id =" +taskId;

            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sqlAll);
            com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(maps));
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            String userName =jsonObject.getString(cTableName+"_single_person");
            //查询表单所有字段
            List<CreateTable> byTableName = createTableService.selectAll(new CreateTable() {{
                this.setTableName(cTableName);
            }});

            //查询表单下面的子表的所有字段
            TableClass byTableClassName = tableClassService.getOne(new QueryWrapper<TableClass>() {{
                this.eq("tableClassName", cTableName);
            }});
            List<TableClass> byTableClassId1 = tableClassService.list(new QueryWrapper<TableClass>() {{
                this.eq("pid", byTableClassName.getTableClassId());
            }});

            //设置流程变量
            Map<String,Object> variables = new HashMap<>();
            for (TableClass tableClass : byTableClassId1) {
                List<TableClass> byTableName1 = tableClassService.findByTableNameList(tableClass.getTableClassName());
                //子表下面的字段都存进去
                if (byTableName1.size()>0){
                    for (int i= 0;i<byTableName1.size();i++){
                        TableClass byTableClassId = tableClassService.getById(byTableName1.get(i).getTableClassId());
                        List<CreateTable> byTableName2 = createTableService.findByTableName(byTableClassId.getTableClassName());
                        String sql = "SELECT * FROM " + byTableClassId.getTableClassName() + " WHERE " + cTableName+"_id =" + taskId;
                        List<Map<String, Object>> mapslist = jdbcTemplate.queryForList(sql);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(mapslist));
                        for (int j = 0;j<jsonArray2.size();j++){
                            JSONObject jsonObject1 = jsonArray2.getJSONObject(j);
                            if (byTableName2.size()>0){
                                for (CreateTable c :byTableName2){
                                    variables.put("$"+c.getField()+"$",jsonObject1.get(c.getField()));
                                }
                            }
                        }

                    }
                }
            }
            //循环给map赋值
            for (CreateTable c :byTableName){
                variables.put("$"+c.getField()+"$",jsonObject.get(c.getField()));
            }

            // 启动流程
            System.out.println("流程实例参数" + formList.getProcessInstanceId());
            ProcessInstance pi = runtimeService.startProcessInstanceById(formList.getProcessInstanceId(),variables);
            // 根据流程实例Id查询任务
            Task task = taskService.createTaskQuery()
                    .processInstanceId(pi.getProcessInstanceId())
                    .singleResult();
            // 根据流程实例Id查询下一节点是谁申请并且通知他
            String assignee = task.getAssignee();
            String Assignee = "";
            if (assignee.equals("提交部门负责人")) {
                Assignee = findDepartmentHead(userName);
            } else if (assignee.equals("提交人部门分管领导")) {
                Assignee = findDepartmentalLeadership(userName);
            }else if(assignee.equals("中心主任")){
                Assignee = findDirector(userName);
            }
            if (!("").equals(Assignee)) {
                taskService.setAssignee(task.getId(), Assignee);
                UserInfo byUserInfoId = userInfoService.getById(Integer.parseInt(Assignee));
                json.put("userInfo",byUserInfoId);

            }else{
                UserInfo byUserInfoId = userInfoService.findByPersonnelId(Integer.parseInt(task.getAssignee()));
                taskService.setAssignee(task.getId(),byUserInfoId.getUserId()+"");
                json.put("userInfo",byUserInfoId);
            }
            //修改状态
            Map<String, Object> map = new HashMap<>();
            map.put(cTableName + "_processInstanceId", pi.getProcessInstanceId());
            map.put(cTableName + "_state", "1");//1：已提交状态
            System.out.println("节点Id" + pi.getProcessInstanceId());
            System.out.println("修改的表名是" + cTableName);
            System.out.println("修改的数据Id是" + taskId);
            String sql = sqlData.updateBaseTwo(cTableName, map, taskId);
            System.out.println(sql);

            int x = jdbcTemplate.update(sql);
            if (x > 0) {
                System.out.println("修改成功" + cTableName + taskId + pi.getProcessInstanceId());
                // 状态修改成功为 2审批中 更新金额
                if(("StandbyFundReturn").equals(cTableName)||(("StandbyFundReturn"))==cTableName){
                    BigDecimal standbyListDetails_xgry_0008 = (BigDecimal) variables.get("StandbyListDetails_xgry_0008"); // 归还备用金 本次归还金额
                    String standbyListDetails_xgry_0001 = (String) variables.get("StandbyListDetails_xgry_0001"); // 归还备用金 编码

                    String sql1 = "SELECT * FROM ApplicationFund WHERE ApplicationFund_code = " + standbyListDetails_xgry_0001;
                    List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql1);
                    Map<String, Object> map1 = mapList.get(0);
                    BigDecimal applicationFund_xgry_0017 = (BigDecimal) map1.get("ApplicationFund_xgry_0017");  // 已冻结金额
                    BigDecimal applicationFund_xgry_0015 = (BigDecimal) map1.get("ApplicationFund_xgry_0015");  // 剩余可用金额

                    // 剩余可用金额 = 剩余可用金额 - 本次冲抵金额
                    applicationFund_xgry_0015 = applicationFund_xgry_0015.subtract(standbyListDetails_xgry_0008);
                    // 已冻结金额 = 终审单据已冻结金额 + 单据提交的本次冲抵金额
                    applicationFund_xgry_0017 = applicationFund_xgry_0017.add(standbyListDetails_xgry_0008);
                    String sqlUpdate = "UPDATE ApplicationFund SET ApplicationFund_xgry_0017 = '" + applicationFund_xgry_0017 + "',ApplicationFund_xgry_0015 = " + applicationFund_xgry_0015 + " WHERE ApplicationFund_code = " + standbyListDetails_xgry_0001;
                    jdbcTemplate.update(sqlUpdate);
                } else if(("TransactionFundReturn").equals(cTableName)||("TransactionFundReturn")==cTableName) { // 归还金额提交后金额为冻结状态
                    BigDecimal transactionFundDetails_xgry_0007 = (BigDecimal) variables.get("TransactionFundDetails_xgry_0007"); // 事务备用金 本次归还金额
                    String transactionFundDetails_xgry_0001 = (String) variables.get("TransactionFundDetails_xgry_0001"); // 事务归还备用金 编码

                    String sql1 = "SELECT * FROM TransactionFund WHERE TransactionFund_code = " + transactionFundDetails_xgry_0001;
                    List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql1);
                    Map<String, Object> map1 = mapList.get(0);
                    BigDecimal transactionFund_xgry_0015 = (BigDecimal) map1.get("TransactionFund_xgry_0015");  // 已冻结金额
                    BigDecimal transactionFund_xgry_0013 = (BigDecimal) map1.get("TransactionFund_xgry_0013");  // 剩余可用金额

                    // 剩余可用金额 = 剩余可用金额 - 本次冲抵金额
                    transactionFund_xgry_0013 = transactionFund_xgry_0013.subtract(transactionFundDetails_xgry_0007);
                    // 已冻结金额 = 终审单据已冻结金额 + 单据提交的本次冲抵金额
                    transactionFund_xgry_0015 = transactionFund_xgry_0015.add(transactionFundDetails_xgry_0007);
                    String sqlUpdate = "UPDATE ApplicationFund SET TransactionFund_xgry_0015 = '" + transactionFund_xgry_0015 + "',TransactionFund_xgry_0013 = " + transactionFund_xgry_0013 + " WHERE ApplicationFund_code = " + transactionFundDetails_xgry_0001;
                    jdbcTemplate.update(sqlUpdate);

                } else if (("ExpensesReimbursement").equals(cTableName)||("ExpensesReimbursement")==cTableName) { // 日常报销
                    // 终审单据  已冻结金额
                    BigDecimal detailsOffsetReserveGoods_xgry_0008 = (BigDecimal) variables.get("DetailsOffsetReserveGoods_xgry_0008"); // 冲抵备用金 本次冲抵金额
                    String detailsOffsetReserveGoods_xgry_0001 = (String) variables.get("DetailsOffsetReserveGoods_xgry_0001"); // 冲抵备用金 编码

                    String sql1 = "SELECT * FROM ApplicationFund WHERE ApplicationFund_code = " + detailsOffsetReserveGoods_xgry_0001;
                    List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql1);
                    Map<String, Object> map1 = mapList.get(0);
                    BigDecimal applicationFund_xgry_0017 = (BigDecimal) map1.get("ApplicationFund_xgry_0017");  // 已冻结金额
                    BigDecimal applicationFund_xgry_0015 = (BigDecimal) map1.get("ApplicationFund_xgry_0015");  // 剩余可用金额

                    // 剩余可用金额 = 剩余可用金额 - 本次冲抵金额
                    applicationFund_xgry_0015 = applicationFund_xgry_0015.subtract(detailsOffsetReserveGoods_xgry_0008);
                    // 已冻结金额 = 终审单据已冻结金额 + 单据提交的本次冲抵金额
                    applicationFund_xgry_0017 = applicationFund_xgry_0017.add(detailsOffsetReserveGoods_xgry_0008);
                    String sqlUpdate = "UPDATE ApplicationFund SET ApplicationFund_xgry_0017 = '" + applicationFund_xgry_0017 + "',ApplicationFund_xgry_0015 = " + applicationFund_xgry_0015 + " WHERE ApplicationFund_code = " + detailsOffsetReserveGoods_xgry_0001;
                    jdbcTemplate.update(sqlUpdate);
                }
                else if (("TravelExpense").equals(cTableName) || ("TravelExpense") == cTableName) { // 差旅费
                    // 终审单据  已冻结金额
                    BigDecimal detailsOfReserveFund_xgry_0008 = (BigDecimal) variables.get("DetailsOfReserveFund_xgry_0008"); // 冲抵备用金 本次冲抵金额
                    String detailsOfReserveFund_xgry_0001 = (String) variables.get("DetailsOfReserveFund_xgry_0001"); // 冲抵备用金 编码

                    String sql1 = "SELECT * FROM ApplicationFund WHERE ApplicationFund_code = " + detailsOfReserveFund_xgry_0001;
                    List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql1);
                    Map<String, Object> map1 = mapList.get(0);
                    BigDecimal applicationFund_xgry_0017 = (BigDecimal) map1.get("ApplicationFund_xgry_0017");  // 已冻结金额
                    BigDecimal applicationFund_xgry_0015 = (BigDecimal) map1.get("ApplicationFund_xgry_0015");  // 剩余可用金额

                    // 剩余可用金额 = 剩余可用金额 - 本次冲抵金额
                    applicationFund_xgry_0015 = applicationFund_xgry_0015.subtract(detailsOfReserveFund_xgry_0008);
                    // 已冻结金额 = 终审单据已冻结金额 + 单据提交的本次冲抵金额
                    applicationFund_xgry_0017 = applicationFund_xgry_0017.add(detailsOfReserveFund_xgry_0008);
                    String sqlUpdate = "UPDATE ApplicationFund SET ApplicationFund_xgry_0017 = '" + applicationFund_xgry_0017 + "',ApplicationFund_xgry_0015 = " + applicationFund_xgry_0015 + " WHERE ApplicationFund_code = " + detailsOfReserveFund_xgry_0001;
                    jdbcTemplate.update(sqlUpdate);
                }
            } else {
                System.out.println("修改失败");
            }
            json.put("msg", "提交成功");
            json.put("assignee", Assignee);
            json.put("taskId", task.getId());
            System.out.println("启动任务成功");
            return json.toString();
        } catch (Exception e) {
            json.put("msg", "提交失败");
            return json.toString();
        }

    }


    /**
     * 查询流程信息
     *
     * @param response
     * @param taskId   流程实例ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getLeaveByTaskId.do", produces = "application/json; charset=utf-8")
    public Result getLeaveByTaskId(HttpServletResponse response, String taskId) throws Exception {
        //测试数据
        //==========================
        taskId = "117508";
        //==========================
        //先根据流程ID查询
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //此处搬迁原BPM没有找到实现类
        Leave leave = leaveService.getById(task.getProcessInstanceId());
        return Result.success(leave);
    }

    /**
     * 查询历史流程批注
     *
     * @param response
     * @param processInstanceId 流程ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/listHistoryCommentWithProcessInstanceId.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result listHistoryCommentWithProcessInstanceId(
            HttpServletResponse response, @RequestParam("taskId") String processInstanceId) throws Exception {

        //测试数据
        //==============================================================
        //processInstanceId = "310011";
        //==============================================================
        if (processInstanceId == null || "".equals(processInstanceId)) {
            return Result.fail("未查询到当前流程");
        }
        List<Comment> commentList = taskService
                .getProcessInstanceComments(processInstanceId);
        // 改变顺序，按原顺序的反向顺序返回list
        Collections.reverse(commentList); //集合元素反转
        return Result.success(commentList);
    }

    /**
     * 查询提交人的所有流程信息
     */
    @RequestMapping(value = "/listHistoryfindProcessInstanceId.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String aaaa(String userId) {
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().startedBy(userId).list();
        return list.toString();
    }

    /**
     * 待办流程分页查询
     *
     * param response
     * @param pageIndex     当前页数
     * @param pageSize     每页显示页数
     * @param s_name   流程名称
     * param userId   流程ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/taskPage.do", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String taskPage(@RequestParam(value = "page",defaultValue = "1") Integer pageIndex,
                           @RequestParam(value = "rows",defaultValue = "50")Integer pageSize, String s_name) throws Exception {
        JSONObject json = new JSONObject();
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        String userId = userInfo.getUserId().toString();
        // 获取总记录数
        System.out.println("用户ID：" + userInfo.getUserId() + "\n" + "名称:" + s_name);
        long total = taskService.createTaskQuery()
                .taskAssignee(userId)
                //.taskNameLike("%"+s_name+"%")
                .count(); // 获取总记录数
        //有想法的话，可以去数据库观察  ACT_RU_TASK 的变化
        List<Task> taskList = taskService.createTaskQuery()
                // 根据用户id查询
                .taskAssignee(userId)
                // 根据任务名称查询
                //.taskNameLike("%"+s_name+"%")
                // 返回带分页的结果集合
                .listPage((pageIndex - 1 ) * pageSize, pageSize);
        System.out.println("taskList-------------------" + taskList);
        //这里需要使用一个工具类来转换一下主要是转成JSON格式
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (Task t : taskList) {
            //根据流程实例ID查询formlistId对应的数据
            System.out.println("流程实例ID" + t.getProcessDefinitionId());
            FormList formlist = formListService.findByProcessInstanceId(t.getProcessDefinitionId());
            //FormList formlist = formListService.findById(Integer.parseInt(t.getFormKey()));
            System.out.println("根据流程实例Id获取cTableName" + formlist.getCTableName());
            String cTableName = formlist.getCTableName();
            Map<String, String> map = new HashMap<>();
            map.put(cTableName + "_processInstanceId", t.getProcessInstanceId());
            String sql = sqlData.findByprocessInstanceId(cTableName, map);
            JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
            List<Map<String, Object>> objs = jdbcTemplate.queryForList(sql);
            json.put("activitiList", objs);
            if (objs.size() > 0) {
                com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(objs));
                JSONObject json1 = jsonArray.getJSONObject(0);
                String taskId = json1.getString(cTableName + "_id");
                String pid = json1.getString(cTableName + "_single_person_id");
                String state = json1.getString(cTableName+"_state");
                UserInfo byUserInfoId = userInfoService.getById(Integer.parseInt(pid));
                Map<String,Object> task = new HashMap<>();
                task.put("id",t.getId());
                task.put("name",t.getName());
                task.put("createTime", DateTimeUtil.dateToStr(t.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                task.put("cTableName",cTableName);
                task.put("taskId",taskId);
                task.put("formlistId",Integer.toString(formlist.getFormListId()));
                task.put("formName",formlist.getFormName());
                task.put("processId",t.getExecutionId());
                if(state.equals(4)||state.equals("4")){
                    task.put("explain",byUserInfoId.getUName()+"被驳回的"+formlist.getFormName());
                }else{
                    task.put("explain",byUserInfoId.getUName()+"提交的"+formlist.getFormName());
                }
                resultList.add(task);
            } else {
                json.put("msg", "当前无待办任务");
            }
        }
        json.put("data", resultList);
        json.put("total", total);
        return json.toString();
    }


    /**
     * 查询历史批注
     *
     * @param response
     * @param taskId   流程ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/listHistoryComment.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result listHistoryComment(HttpServletResponse response, @RequestParam("taskId") String taskId) throws Exception {
        if (taskId == null) {
            taskId = "";
        }
        HistoricTaskInstance hti = historyService.createHistoricTaskInstanceQuery()
                .taskId(taskId)
                .singleResult();
        List<Comment> commentList = null;
        if (hti != null) {
            commentList = taskService.getProcessInstanceComments(hti.getProcessInstanceId());
            // 改变顺序，按原顺序的反向顺序返回list
            Collections.reverse(commentList); //集合元素反转
        }
        return Result.success(null == commentList?"当前没有审核记录":commentList);
    }

    /**
     * 查看流程正常走完的历史流程表 :  act_hi_actinst
     *
     * @param pageSize
     * @param pageIndex
     * @param s_name
     * @param groupId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/finishedList.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result finishedList(@RequestParam(value = "rows",defaultValue = "1") Integer pageSize,
                               @RequestParam(value = "pageIndex",defaultValue = "50") Integer pageIndex,
                               @RequestParam("s_name")String s_name, @RequestParam("groupId")String groupId) throws Exception {
        JSONObject json = new JSONObject();
        if (s_name == null) {
            s_name = "";
        }
        //创建流程历史实例查询
        List<HistoricTaskInstance> histList = historyService.createHistoricTaskInstanceQuery()
                .taskCandidateGroup(groupId)//根据角色名称查询
                .taskNameLike("%" + s_name + "%")
                .listPage((pageIndex-1)*pageSize,pageSize);

        long histCount = historyService.createHistoricTaskInstanceQuery()
                .taskCandidateGroup(groupId)
                .taskNameLike("%" + s_name + "%")
                .count();
        List<Map<String,Object>> result = new ArrayList<>();
        //这里递出没有用的字段，免得给前端页面做成加载压力
        for (HistoricTaskInstance hti : histList) {
            Map<String,Object> task = new HashMap<>();
            task.put("id",hti.getId());
            task.put("name",hti.getName());
            task.put("createTime",DateTimeUtil.dateToStr(hti.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            task.put("endTime",hti.getEndTime());
            result.add(task);
        }
        json.put("total", histCount);
        return Result.success(result,histCount);
    }

    /**
     * 根据任务id查询流程实例的具体执行过程
     *
     * @param taskId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/listAction.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result listAction(String taskId, HttpServletResponse response) throws Exception {
        JSONObject json = new JSONObject();
        HistoricTaskInstance hti = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        String processInstanceId = hti.getProcessInstanceId(); // 获取流程实例id
        List<HistoricActivityInstance> haiList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
        return Result.success(haiList);
    }

    /**
     * 审批
     *
     * @param taskId    任务id
     * param leaveDays 请假天数
     * @param comment   批注信息
     * param state     审核状态 1 通过 2 驳回
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/audit_bz.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String audit_bz(String taskId, String comment, HttpSession session, String pid, String fromId) throws Exception {
        System.out.println(pid);
        System.out.println("FromId" + fromId);
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        JSONObject json = new JSONObject();
        //首先根据ID查询任务
        System.out.println(taskId);
        System.out.println("审核意见" + comment);

        try {
            Task task = taskService.createTaskQuery() // 创建任务查询
                    .taskId(taskId) // 根据任务id查询
                    .singleResult();
            //取得角色用户登入的session对象
            UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            // 获取流程实例id
            String processInstanceId = task.getProcessInstanceId();
            String processDefinitionId = task.getProcessDefinitionId();

            FormList formlist = formListService.findByProcessInstanceId(processDefinitionId);
            System.out.println("根据流程实例Id获取cTableName" + formlist.getCTableName());

            String cTableName = formlist.getCTableName();
            String sqlAll = "select * from " + cTableName +" where "+cTableName+"_id =" +fromId;
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sqlAll);
            com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(mapList));
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            //查询表单所有字段
            List<CreateTable> byTableName = createTableService.findByTableName(cTableName);
            TableClass byTableClassName = tableClassService.findByTableClassName(cTableName);

            List<TableClass> byTableClassId1 = tableClassService.findBytableClassIdP(byTableClassName.getTableClassId());
            //设置流程变量
            Map<String,Object> variables = new HashMap<>();
            for (TableClass tableClass : byTableClassId1) {
                List<TableClass> byTableName1 = tableClassService.findByTableNameList(tableClass.getTableClassName());
                //子表下面的字段都存进去
                if (byTableName1.size()>0){
                    for (int i= 0;i<byTableName1.size();i++){
                        TableClass byTableClassId = tableClassService.getById(byTableName1.get(i).getTableClassId());
                        List<CreateTable> byTableName2 = createTableService.findByTableName(byTableClassId.getTableClassName());
                        String sql = "SELECT * FROM " + byTableClassId.getTableClassName() + " WHERE " + cTableName+"_id =" + taskId;
                        List<Map<String, Object>> mapslist = jdbcTemplate.queryForList(sql);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(mapslist));
                        for (int j = 0;j<jsonArray2.size();j++){
                            JSONObject jsonObject1 = jsonArray2.getJSONObject(j);
                            if (byTableName2.size()>0){
                                for (CreateTable c :byTableName2){
                                    variables.put("$"+c.getField()+"$",jsonObject1.get(c.getField()));
                                }
                            }
                        }

                    }
                }
            }
            //循环给map赋值
            for (CreateTable c :byTableName){
                variables.put("$"+c.getField()+"$",jsonObject.get(c.getField()));
            }
            // 添加批注信息
            taskService.addComment(taskId, processInstanceId, comment);
            // 完成任务
            taskService.complete(taskId,variables);
            List<Task> list = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
            if (list.size() > 0 && list != null) {
                Task task1 = list.get(0);
                if (task1 != null && !("").equals(task1)) {
                    String sql = "update " + cTableName + " set " + cTableName + "_state =" + 2 + " where " + cTableName + "_id " + "=" + fromId;
                    System.out.println(sql);
                    int update = jdbcTemplate.update(sql);
                    System.out.println("单据已审批");
                }
                if (pid != null && !pid.equals("") && !"undefined".equals(pid)) {
                    UserInfo byPersonnelId = userInfoService.findByPersonnelId(Integer.parseInt(pid));
                    json.put("userInfo",byPersonnelId);
                    Integer userId = byPersonnelId.getUserId();
                    if (task1 != null) {
                        taskService.setAssignee(task1.getId(), userId+"");
                    }
                }
            } else {
                if(("StandbyFundReturn").equals(cTableName)||(("StandbyFundReturn"))==cTableName){
                    String sql1 = "select * from StandbyListDetails where StandbyFundReturn_id =" +fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int i = 0;i<jsonArray1.size();i++){
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                        BigDecimal standbyListDetails_xgry_0006 = (BigDecimal)jsonObject1.get("StandbyListDetails_xgry_0006");
                        BigDecimal standbyListDetails_xgry_0008 = (BigDecimal)jsonObject1.get("StandbyListDetails_xgry_0008");
                        String sql2 = "update ApplicationFund set ApplicationFund_xgry_0014 ="+ standbyListDetails_xgry_0006.add(standbyListDetails_xgry_0008)+" where ApplicationFund_code ="+jsonObject1.getString("StandbyListDetails_xgry_0001");
                        jdbcTemplate.update(sql2);
                    }
                }else if(("TransactionFundReturn").equals(cTableName)||("TransactionFundReturn")==cTableName) {
                    String sql1 = "select * from TransactionFundDetails where TransactionFundReturn_id =" + fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int i = 0; i < jsonArray1.size(); i++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                        BigDecimal transactionFundDetails_xgry_0007 = (BigDecimal)jsonObject1.get("TransactionFundDetails_xgry_0007");
                        BigDecimal transactionFundDetails_xgry_0005 = (BigDecimal)jsonObject1.get("TransactionFundDetails_xgry_0005");
                        String sql2 = "update TransactionFund set TransactionFund_xgry_0012 =" +transactionFundDetails_xgry_0005.add(transactionFundDetails_xgry_0007) + " where TransactionFund_code =" + jsonObject1.getString("TransactionFundDetails_xgry_0001");
                        jdbcTemplate.update(sql2);
                    }
                } else if (("ExpensesReimbursement").equals(cTableName)||("ExpensesReimbursement")==cTableName) {
//                    if (("ExpensesReimbursement").equals(cTableName)||("ExpensesReimbursement")==cTableName) {
//                        // 终审单据  已冻结金额
//                        BigDecimal detailsOffsetReserveGoods_xgry_0008 = (BigDecimal) variables.get("DetailsOffsetReserveGoods_xgry_0008"); // 冲抵备用金 本次冲抵金额
//                        String detailsOffsetReserveGoods_xgry_0001 = (String) variables.get("DetailsOffsetReserveGoods_xgry_0001"); // 冲抵备用金 编码
//
//                        String sql1 = "SELECT ApplicationFund_xgry_0017 FROM ApplicationFund WHERE ApplicationFund_code = " + detailsOffsetReserveGoods_xgry_0001;
//                        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql1);
//                        Map<String, Object> map1 = mapList.get(0);
//                        BigDecimal applicationFund_xgry_0017 = (BigDecimal) map1.get("ApplicationFund_xgry_0017");
//
//                        String sqlUpdate = "UPDATE ApplicationFund SET ApplicationFund_xgry_0017 = '" + applicationFund_xgry_0017.add(detailsOffsetReserveGoods_xgry_0008) + "' WHERE ApplicationFund_code = " + detailsOffsetReserveGoods_xgry_0001;
//                        jdbcTemplate.update(sqlUpdate);
//                    }
                    String sql1 = "select * from DetailsOffsetReserveGoods where ExpensesReimbursement_id =" + fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int i = 0; i < jsonArray1.size(); i++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                        BigDecimal DetailsOffsetReserveGoods_xgry_0008 = (BigDecimal)jsonObject1.get("DetailsOffsetReserveGoods_xgry_0008"); // 本次冲抵金额
                        String DetailsOffsetReserveGoods_xgry_0001 = (String) jsonObject1.get("DetailsOffsetReserveGoods_xgry_0001"); // 终审单据编号

                        String sql2 = "select * from ApplicationFund where ApplicationFund_code = '" + DetailsOffsetReserveGoods_xgry_0001 + "'";
                        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                        JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                        BigDecimal applicationFund_xgry_0011 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0011"); // 以抵金额
                        BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额

                        String sql3 = "update ApplicationFund set ApplicationFund_xgry_0011 =" + applicationFund_xgry_0011.add(DetailsOffsetReserveGoods_xgry_0008) + ",ApplicationFund_xgry_0017 = " + applicationFund_xgry_0017.subtract(DetailsOffsetReserveGoods_xgry_0008) + " where ApplicationFund_code =" + DetailsOffsetReserveGoods_xgry_0001;
                        jdbcTemplate.update(sql3);
                    }
                } else if (("TravelExpense").equals(cTableName)||("TravelExpense")==cTableName) {
                    String sql1 = "select * from DetailsOfReserveFund where DetailsOfReserveFund_id =" + fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int i = 0; i < jsonArray1.size(); i++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                        BigDecimal detailsOfReserveFund_xgry_0008 = (BigDecimal)jsonObject1.get("DetailsOfReserveFund_xgry_0008"); // 本次冲抵金额
                        String detailsOfReserveFund_xgry_0001 = jsonObject1.getString("DetailsOfReserveFund_xgry_0001"); // 终审单据编号

                        String sql2 = "select * from ApplicationFund where ApplicationFund_code = '" + detailsOfReserveFund_xgry_0001 + "'";
                        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                        JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                        BigDecimal applicationFund_xgry_0011 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0011"); // 以抵金额
                        BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额

                        // sum1 以抵金额 = 终审单据以抵金额 + 本次冲抵金额
                        BigDecimal sum1 = applicationFund_xgry_0011.add(detailsOfReserveFund_xgry_0008);
                        // sum2 已冻结金额 = 终审单据已冻结金额 - 本次冲抵金额
                        BigDecimal sum2 = applicationFund_xgry_0017.subtract(detailsOfReserveFund_xgry_0008);

                        String sql3 = "update ApplicationFund set ApplicationFund_xgry_0011 =" + sum1 + ",ApplicationFund_xgry_0017 = " + sum2 + "  where ApplicationFund_code =" + detailsOfReserveFund_xgry_0001;
                        jdbcTemplate.update(sql3);
                    }
                }
                String sql = "update " + cTableName + " set " + cTableName + "_state =" + 3 +" , "+cTableName+"_audit_time = "+ "'"+ DateTimeUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss")+"'" + " where " + cTableName + "_id " + "=" + fromId;
                jdbcTemplate.update(sql);
                System.out.println("单据已终审");
            }
            json.put("type", "success");
            return json.toString();
        } catch (Exception e) {
            json.put("type", "error");
            return json.toString();
        }

    }



    /**
     * 2019-04-17  23：39
     * <p>
     * 委托任务
     * 将指定的任务进行委托处理
     *
     * @param taskId
     * @param assignee
     */
    @RequestMapping(value = "/delegateTask.do", method = RequestMethod.POST)
    public Result delegateTask(@RequestBody HttpSession session, String taskId, String assignee) throws Exception {
        //==================
        taskId = "322503";
        assignee = "8";
        //=====================
        taskService.delegateTask(taskId, assignee);
        return Result.success();
    }

    /**
     * 2019-04-17  23：39
     * <p>
     * 根据taskId解决被委托的任务,动态传值设置变量，返回给owner设置任务人；
     *
     * @param taskId
     * @param variables
     */
    @RequestMapping(value = "/resolveTaskToOwner.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result resolveTaskToOwner(@RequestParam("taskId") String taskId, Map<String, Object> variables) {
        //==================
        //taskId ="322503";
        //===================
        String msg = "异常";
        //根据taskId提取任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task.getOwner() != null && !task.getOwner().equals("null")) {
            DelegationState delegationState = task.getDelegationState();
            if (delegationState.toString().equals("RESOLVED")) {
                msg =  "此委托任务已是完结状态";
            } else if (delegationState.toString().equals("PENDING")) {
                //如果是委托任务需要做处理
                taskService.resolveTask(taskId, variables);
                msg = "委托任务处理完成，返回至委托人";
            } else {
                msg =  "此任务不是委托任务";
            }
        }
        return Result.success(msg);
    }


    /**
     * 根据taskId解决被委托的任务并进行到下一个节点，动态传值设置变量，直接跳转到下一节点；
     */
    @RequestMapping(value = "/resolveTask.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result resolveTask(@RequestBody String taskId, Map<String, Object> variables) {

        //==================
        taskId = "322503";
        //===================
        String msg = "异常";
        //根据taskId提取任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task.getOwner() != null && !task.getOwner().equals("null")) {
            DelegationState delegationState = task.getDelegationState();
            if (delegationState.toString().equals("RESOLVED")) {
                msg = "此委托任务已是完结状态";
            } else if (delegationState.toString().equals("PENDING")) {
                //如果是委托任务需要做处理
                taskService.resolveTask(taskId);
                taskService.complete(taskId, variables);
                msg  =  "委托任务处理完成,跳转到下一节点";
            } else {
                msg = "此任务不是委托任务";
            }
        }
        return Result.success(msg);
    }


//===================================================================================驳回======================================

    /**
     * 驳回至哪一步操作
     * 2019-04-18 0：44
     *
     * @param taskId     当前任务ID     ID_
     * @param activityId 目标节点任务ID  TASK_DEF_KEY_
     * @param variables  流程变量
     * @throws Exception
     */
    @RequestMapping(value = "/backgroud.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public void backgroud(@RequestBody String taskId, String activityId, Map<String, Object> variables) {
        // 当前节点
        ActivityImpl currActivity = findActivitiImpl(taskId, null);
        // 清空当前流向
        List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);
        // 创建新流向
        TransitionImpl newTransition = currActivity.createOutgoingTransition();
        // 目标节点
        ActivityImpl pointActivity = findActivitiImpl(taskId, activityId);
        // 设置新流向的目标节点
        newTransition.setDestination(pointActivity);
        // 执行转向任务
        taskService.complete(taskId);
        // 删除目标节点新流入
        pointActivity.getIncomingTransitions().remove(newTransition);

        // 还原以前流向
        restoreTransition(currActivity, oriPvmTransitionList);
    }


    /**
     * 清空指定活动节点现有流向,且将清空的现有流向返回
     *
     * @param activityImpl 活动节点
     * @return 节点流向集合
     */
    public static List<PvmTransition> clearTransition(ActivityImpl activityImpl) {
        // 存储当前节点所有流向临时变量
        List<PvmTransition> oriPvmTransitionList = new ArrayList<>();
        // 获取当前节点所有流向，存储到临时变量，然后清空
        List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
        for (PvmTransition pvmTransition : pvmTransitionList) {
            oriPvmTransitionList.add(pvmTransition);
        }
        pvmTransitionList.clear();

        return oriPvmTransitionList;
    }

    /**
     * 根据任务ID和节点ID获取活动节点 <br>
     *
     * @param taskId
     * @param activityId 活动节点ID <br>
     *                   如果为null或""，则默认查询当前活动节点 <br>
     *                   如果为"end"，则查询结束节点 <br>
     * @return
     * @throws Exception
     */
    private ActivityImpl findActivitiImpl(String taskId, String activityId) {
        TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId(
                taskId).singleResult();
        if (task == null) {
            return null;
        }

        // 取得流程定义
        //ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(taskService.createTaskQuery().taskId(taskId).singleResult().getProcessDefinitionId());
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(task.getProcessDefinitionId());
        // 获取当前活动节点ID
        if (StringUtils.isEmpty(activityId)) {
            activityId = task.getTaskDefinitionKey();
            System.out.println(activityId);
        }
        // 根据流程定义，获取该流程实例的结束节点
        // ProcessDefinitionImpl processDefinitionImpl = (ProcessDefinitionImpl) getReadOnlyProcessDefinitionByProcDefId(processDefinition.getId());
        if (activityId.toUpperCase().equals("END")) {

            for (ActivityImpl activityImpl : processDefinition.getActivities()) {
                List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
                if (pvmTransitionList.isEmpty()) {
                    return activityImpl;
                }
            }
        }
        String s = activityId.toUpperCase();
        // 根据节点ID，获取对应的活动节点
        ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinition).findActivity(activityId);
        // 此处改动，无法获取到对应的活动节点，所以此处采用迂回的方式，如果前面可以取到则跳过，如果没有取到则自己取
        if (activityImpl == null) {
            List<ActivityImpl> activities = ((ProcessDefinitionImpl) processDefinition).getActivities();
            for (ActivityImpl actImpl : activities) {
                if (activityId.contains(actImpl.getId())) {
                    activityImpl =actImpl;
                    break;
                }
            }
        }
        return activityImpl;
    }


    /**
     * 清空指定节点现有流向，且将新流向接入
     *
     * @param activityImpl         活动节点
     * @param oriPvmTransitionList 新流向节点集合
     */
    private void restoreTransition(ActivityImpl activityImpl, List<PvmTransition> oriPvmTransitionList) {
        // 清空现有流向
        List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
        pvmTransitionList.clear();
        // 还原以前流向
        for (PvmTransition pvmTransition : oriPvmTransitionList) {
            pvmTransitionList.add(pvmTransition);
        }
    }

//===================================================================================驳回======================================
//===============================查询当前任务的可驳回节点信息=============================================//

    /**
     * 驳回至哪一步操作
     * 2019-04-18 0：44
     *
     * param taskId     当前任务ID     ID_
     * param activityId 目标节点任务ID  TASK_DEF_KEY_
     * param variables  流程变量
     * @throws Exception
     */
    @RequestMapping(value = "/findbackList.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result findbackList(@RequestBody String procinstId) throws Exception {
        String sql = "SELECT * FROM [dbo].[ACT_HI_TASKINST] WHERE PROC_INST_ID_ = " + procinstId + " ORDER BY START_TIME_";
        //json.put("data", jdbCutils.excuteQuery(sql, null));
        JdbcTemplate jdbcTemplate = new MSFactory().getJdbcTemplate();
        return Result.success(jdbcTemplate.queryForList(sql));
    }
//===============================查询当前任务的可驳回节点信息=============================================//
    //===============================查询上一步节点信息=============================================//

    /**
     * 驳回至上一步操作
     * 2019-04-18 0：44
     *
     * param taskId     当前任务ID     ID_
     * param activityId 目标节点任务ID  TASK_DEF_KEY_
     * param variables  流程变量
     * @throws Exception
     */
    private String findup(String procinstId) throws Exception {
        JdbcTemplate jdbcTemplate = new MSFactory().getJdbcTemplate();
        String sql = "SELECT top 1 t.TASK_DEF_KEY_ FROM (SELECT top 2 * FROM [dbo].[ACT_HI_TASKINST] WHERE PROC_INST_ID_ = '" + procinstId + "' ORDER BY START_TIME_ desc) t ORDER BY START_TIME_";
        String activityId = (String) jdbcTemplate.queryForList(sql).toString();

        return activityId;
    }
//===============================查询当前任务的可驳回节点信息=============================================//

    //========================================这个方法是终止流程============================================//

    /**
     * taskId:任务id
     * opinion：意见
     */
    @RequestMapping(value = "/endTask.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String endTask(@RequestParam("taskId") String taskId, String opinion, @RequestParam("fromId") String fromId) throws Exception {
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        //taskId = "327502";
        System.out.println(fromId);
        JSONObject json = new JSONObject();
        //根据taskID查询任务          
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processDefinitionId = task.getProcessDefinitionId();
        ActivityImpl endActivity = findActivitiImpl(taskId, "end");
        if (endActivity == null) {
            json.put("msg", "未中止");
        }
        // 获取当前活动节点ID
        //String activityId = task.getTaskDefinitionKey();  
        Map<String, Object> variables = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(opinion)) {    //审核意见
            variables.put("驳回意见", opinion);
        }
        // 跳转节点为空，默认提交操作  
        if (StringUtils.isEmpty(endActivity.getId())) {
            if (!StringUtils.isEmpty(task.getOwner())) {
                // 被委派人处理完成任务
                taskService.resolveTask(task.getId(), variables);
            }
            taskService.complete(taskId, variables);
        } else {// 流程转向操作  
            //turnTransition(taskId, activityId, variables);
            // 当前节点  
            ActivityImpl currActivity = findActivitiImpl(taskId, null);
            // 清空当前流向    
            // 存储当前节点所有流向临时变量  
            List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();
            // 获取当前节点所有流向，存储到临时变量，然后清空  
            List<PvmTransition> pvmTransitionList = currActivity
                    .getOutgoingTransitions();
            for (PvmTransition pvmTransition : pvmTransitionList) {
                oriPvmTransitionList.add(pvmTransition);
            }
            pvmTransitionList.clear();
            // 创建新流向  
            TransitionImpl newTransition = currActivity.createOutgoingTransition();
            // 目标节点  
            ActivityImpl pointActivity = findActivitiImpl(taskId, endActivity.getId());
            // 设置新流向的目标节点  
            newTransition.setDestination(pointActivity);
            if (!StringUtils.isEmpty(task.getOwner())) {
                // 被委派人处理完成任务
                taskService.resolveTask(task.getId(), variables);
            }
            // 执行转向任务  
            taskService.complete(taskId, variables);
            // 删除目标节点新流入  
            pointActivity.getIncomingTransitions().remove(newTransition);
            // 还原以前流向  
            //restoreTransition(currActivity, oriPvmTransitionList);
            // 清空现有流向  
            List<PvmTransition> pvmTransitionListC = currActivity.getOutgoingTransitions();
            pvmTransitionListC.clear();
            // 还原以前流向
            for (PvmTransition pvmTransition : oriPvmTransitionList) {
                pvmTransitionListC.add(pvmTransition);
            }
        }
        FormList formlist = formListService.findByProcessInstanceId(processDefinitionId);
        System.out.println("根据流程实例Id获取cTableName" + formlist.getCTableName());
        String cTableName = formlist.getCTableName();
        String sql = "update " + cTableName + " set " + cTableName + "_state =" + 5 + " where " + cTableName + "_id " + "=" + fromId;
        int update = jdbcTemplate.update(sql);
        if (update > 0) {
            json.put("type", "sucess");
        } else {
            json.put("type", "error");
        }
        System.out.println("单据被中止");
        return json.toString();
    }

    @RequestMapping(value = "/cancelTask.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result cancelTask(@RequestParam("cTableName") String cTableName,@RequestParam("formId")String formId,@RequestParam("id") String id,Map<String,Object>variables) throws Exception {
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        String dataMsg = null;
        String sql = "select "+cTableName+"_processInstanceId from "+cTableName +" where "+cTableName+"_id = "+ id;
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(mapList));
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        String processInstanceId = jsonObject.getString(cTableName + "_processInstanceId");
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        if(task==null){
            dataMsg = "单据未提交无法撤销";
        }else{
            int formListId = Integer.parseInt(formId);
            FormList formList = formListService.getById(formListId);
            List<Task> list = taskService.createTaskQuery().processDefinitionId(formList.getProcessInstanceId()).list();
            for (int i=0;i<list.size();i++){
                if(list.get(i).getId().equals(task.getId())){
                    // 当前节点  
                    ActivityImpl currActivity = findActivitiImpl(task.getId(), null);
                    // 清空当前流向
                    List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);
                    // 创建新流向  
                    TransitionImpl newTransition = currActivity.createOutgoingTransition();
                    // 目标节点  
                    ActivityImpl pointActivity = findActivitiImpl(task.getId(), "end");
                    //设置新流向
                    newTransition.setDestination(pointActivity);
                    // 执行转向任务  
                    taskService.complete(task.getId(), variables);
                    // 删除目标节点新流入  
                    pointActivity.getIncomingTransitions().remove(newTransition);
                    // 还原以前流向  
                    restoreTransition(currActivity, oriPvmTransitionList);
                    String sql1 = "update " + cTableName + " set " + cTableName + "_state =" + 6 + " where " + cTableName + "_id " + "=" + id;
                    jdbcTemplate.update(sql1);
                    dataMsg = "撤销成功";
                    System.out.println("单据被撤销");

                    // 撤销成功更新金额
                    if(("StandbyFundReturn").equals(cTableName)||(("StandbyFundReturn"))==cTableName){
                        String sql2 = "select * from StandbyListDetails where StandbyFundReturn_id =" + id;
                        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                        for (int j = 0; j < jsonArray1.size(); j++) {
                            JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                            BigDecimal standbyListDetails_xgry_0008 = (BigDecimal)jsonObject1.get("StandbyListDetails_xgry_0008"); // 本次归还金额
                            String standbyListDetails_xgry_0001 = (String) jsonObject1.get("StandbyListDetails_xgry_0001");

                            String sql3 = "select * from ApplicationFund where ApplicationFund_code = '" + standbyListDetails_xgry_0001 + "'";
                            List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql3);
                            com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                            JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                            BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额
                            BigDecimal applicationFund_xgry_0015 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0015"); // 剩余可用金额

                            // 已冻结金额 = 已冻结金额 - 本次冲抵金额
                            applicationFund_xgry_0017 = applicationFund_xgry_0017.subtract(standbyListDetails_xgry_0008);
                            // 终审单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                            applicationFund_xgry_0015 = applicationFund_xgry_0015.add(standbyListDetails_xgry_0008);
                            String sql4 = "update ApplicationFund set ApplicationFund_xgry_0017 =" + applicationFund_xgry_0017 + ",ApplicationFund_xgry_0015 = " + applicationFund_xgry_0015 + " where ApplicationFund_code =" + standbyListDetails_xgry_0001;
                            jdbcTemplate.update(sql4);
                        }
                    } else if(("TransactionFundReturn").equals(cTableName)||("TransactionFundReturn")==cTableName) { // 归还金额撤销后更新金额
                        String sql2 = "select * from TransactionFundDetails where TransactionFundDetails_id =" + id;
                        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                        for (int j = 0; j < jsonArray1.size(); j++) {
                            JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                            BigDecimal transactionFundDetails_xgry_0007 = (BigDecimal)jsonObject1.get("TransactionFundDetails_xgry_0007"); // 本次归还金额
                            String transactionFundDetails_xgry_0001 = (String) jsonObject1.get("TransactionFundDetails_xgry_0001");

                            String sql3 = "select * from TransactionFundReturn where TransactionFundReturn_code = '" + transactionFundDetails_xgry_0001 + "'";
                            List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql3);
                            com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                            JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                            BigDecimal transactionFund_xgry_0015 = (BigDecimal) jsonObject2.get("TransactionFund_xgry_0015"); // 已冻结金额
                            BigDecimal transactionFund_xgry_0013 = (BigDecimal) jsonObject2.get("TransactionFund_xgry_0013"); // 剩余可用金额

                            // 已冻结金额 = 已冻结金额 - 本次冲抵金额
                            transactionFund_xgry_0015 = transactionFund_xgry_0015.subtract(transactionFundDetails_xgry_0007);
                            // 终审单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                            transactionFund_xgry_0013 = transactionFund_xgry_0013.add(transactionFundDetails_xgry_0007);
                            String sql4 = "update ApplicationFund set TransactionFund_xgry_0015 =" + transactionFund_xgry_0015 + ",TransactionFund_xgry_0013 = " + transactionFund_xgry_0013 + " where ApplicationFund_code =" + transactionFundDetails_xgry_0001;
                            jdbcTemplate.update(sql4);
                        }
                    } else if (("ExpensesReimbursement").equals(cTableName)||("ExpensesReimbursement")==cTableName) { // 日常费用报销
                        String sql2 = "select * from DetailsOffsetReserveGoods where ExpensesReimbursement_id =" + id;
                        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                        for (int j = 0; j < jsonArray1.size(); j++) {
                            JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                            BigDecimal DetailsOffsetReserveGoods_xgry_0008 = (BigDecimal)jsonObject1.get("DetailsOffsetReserveGoods_xgry_0008"); // 本次冲抵金额
                            String DetailsOffsetReserveGoods_xgry_0001 = (String) jsonObject1.get("DetailsOffsetReserveGoods_xgry_0001"); // 终审单据编号

                            String sql3 = "select * from ApplicationFund where ApplicationFund_code = '" + DetailsOffsetReserveGoods_xgry_0001 + "'";
                            List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql3);
                            com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                            JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                            BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额
                            BigDecimal applicationFund_xgry_0015 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0015"); // 剩余可用金额

                            // 已冻结金额 = 已冻结金额 - 本次冲抵金额
                            applicationFund_xgry_0017 = applicationFund_xgry_0017.subtract(DetailsOffsetReserveGoods_xgry_0008);
                            // 终审单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                            applicationFund_xgry_0015 = applicationFund_xgry_0015.add(DetailsOffsetReserveGoods_xgry_0008);
                            String sql4 = "update ApplicationFund set ApplicationFund_xgry_0017 =" + applicationFund_xgry_0017 + ",ApplicationFund_xgry_0015 = " + applicationFund_xgry_0015 + " where ApplicationFund_code =" + DetailsOffsetReserveGoods_xgry_0001;
                            jdbcTemplate.update(sql4);
                        }
                    }
                    else if (("TravelExpense").equals(cTableName)||("TravelExpense")==cTableName) { // 差旅费报销
                        String sql2 = "select * from DetailsOfReserveFund where TravelExpense_id =" + id;
                        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                        for (int j = 0; j < jsonArray1.size(); j++) {
                            JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                            BigDecimal detailsOfReserveFund_xgry_0008 = (BigDecimal)jsonObject1.get("DetailsOfReserveFund_xgry_0008"); // 本次冲抵金额
                            String detailsOfReserveFund_xgry_0001 = jsonObject1.getString("DetailsOfReserveFund_xgry_0001"); // 终审单据编号

                            String sql3 = "select * from ApplicationFund where ApplicationFund_code = '" + detailsOfReserveFund_xgry_0001 + "'";
                            List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql3);
                            com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                            JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                            BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额
                            BigDecimal applicationFund_xgry_0015 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0015"); // 剩余可用金额

                            // sum1 终身单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                            BigDecimal sum1 = applicationFund_xgry_0015.add(detailsOfReserveFund_xgry_0008);
                            // sum2 已冻结金额 = 终审单据已冻结金额 - 本次冲抵金额
                            BigDecimal sum2 = applicationFund_xgry_0017.subtract(detailsOfReserveFund_xgry_0008);

                            String sql4 = "update ApplicationFund set ApplicationFund_xgry_0015 =" + sum1 + ",ApplicationFund_xgry_0017 = " + sum2 + "  where ApplicationFund_code =" + detailsOfReserveFund_xgry_0001;
                            jdbcTemplate.update(sql4);
                        }
                    }
                }
            }
        }
        return Result.success(HttpStatus.OK.getReasonPhrase(),dataMsg);
    }

    /**
     * 控制台我的审批的撤销功能
     * @param cTableName
     * @param id
     * @param variables
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cancelMyTask.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result cancelMyTask(@RequestParam("cTableName") String cTableName,@RequestParam("id") String id,Map<String,Object>variables) throws Exception {
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        String dataMsg = null;
        String sql = "select "+cTableName+"_processInstanceId from "+cTableName +" where "+cTableName+"_id = "+ id;
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(mapList));
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        String processInstanceId = jsonObject.getString(cTableName + "_processInstanceId");
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        if(task==null){
            dataMsg = "单据未提交无法撤销";
        }else{
            FormList formList = formListService.findByCtableName(cTableName);
            List<Task> list = taskService.createTaskQuery().processDefinitionId(formList.getProcessInstanceId()).list();
            for (int i=0;i<list.size();i++){
                if(list.get(i).getId().equals(task.getId())){
                    // 当前节点  
                    ActivityImpl currActivity = findActivitiImpl(task.getId(), null);
                    // 清空当前流向
                    List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);
                    // 创建新流向  
                    TransitionImpl newTransition = currActivity.createOutgoingTransition();
                    // 目标节点  
                    ActivityImpl pointActivity = findActivitiImpl(task.getId(), "end");
                    //设置新流向
                    newTransition.setDestination(pointActivity);
                    // 执行转向任务  
                    taskService.complete(task.getId(), variables);
                    // 删除目标节点新流入  
                    pointActivity.getIncomingTransitions().remove(newTransition);
                    // 还原以前流向  
                    restoreTransition(currActivity, oriPvmTransitionList);
                    String sql1 = "update " + cTableName + " set " + cTableName + "_state =" + 6 + " where " + cTableName + "_id " + "=" + id;
                    jdbcTemplate.update(sql1);
                    dataMsg = "撤销成功";
                    System.out.println("单据被撤销");
                }
            }
        }
        return Result.success(HttpStatus.OK.getReasonPhrase(),dataMsg);
    }

//=============================================================这个方法是终止流程============================================//

//=============================================================挂起======================================================//


//=============================================================挂起======================================================//


//=============================================================恢复======================================================//


//=============================================================恢复======================================================//


//=============================================================委托流程列表查询======================================================//


//=============================================================委托流程列表查询======================================================//


//==========================================================获取高亮节点图片id======================================================//
    /**
     * 读取带跟踪的图片高亮显示
     */
    @RequestMapping(value = "/getView.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public void test(HttpServletResponse response, @RequestParam("processInstanceId") String processInstanceId) throws Exception {
        //获取历史流程实例
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

        List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceEndTime().asc().list();
        //高亮环节id集合
        List<String> highLightedActivitis = new ArrayList<String>();
        //高亮线路id集合
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity, highLightedActivitList);

        //当前流程实例执行到哪个节点
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();// 执行实例

        if(execution!=null){
            highLightedActivitis.add(execution.getActivityId());
        }else{
            for(HistoricActivityInstance tempActivity : highLightedActivitList){
                String activityId = tempActivity.getActivityId();
                highLightedActivitis.add(activityId);
            }
        }
        //中文显示的是口口口，设置字体就好了
        //InputStream imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis,highLightedFlows,"宋体","宋体",null,1.0);
        InputStream imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis, highLightedFlows, "宋体", "宋体", "宋体", null, 1.0);
        //单独返回流程图，不高亮显示
//		InputStream imageStream = diagramGenerator.generatePngDiagram(bpmnModel);
        // 输出资源内容到相应对象
        byte[] b = new byte[1024];
        int len;
        while ((len = imageStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }

    }

    /**
     * 获取需要高亮的线
     *
     * @param processDefinitionEntity
     * @param historicActivityInstances
     * @return
     */
    private List<String> getHighLightedFlows(
            ProcessDefinitionEntity processDefinitionEntity,
            List<HistoricActivityInstance> historicActivityInstances) {
        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {// 对历史流程节点进行遍历
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());// 得到节点定义的详细信息
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances
                        .get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances
                        .get(j + 1);// 后续第二个节点
                if (activityImpl1.getStartTime().equals(
                        activityImpl2.getStartTime())) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            List<PvmTransition> pvmTransitions = activityImpl
                    .getOutgoingTransitions();// 取出节点的所有出去的线
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                        .getDestination();
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }


//==========================================================获取高亮节点图片id======================================================//


    //==========================================================获取下一节点信息======================================================//

    /**
     * 获取下一个用户任务用户组信息
     *
     * param String taskId     任务Id信息
     * @return 下一个用户任务用户组信息
     * @throws Exception
     */
    @RequestMapping(value = "/getNextTaskGroup.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getNextTaskGroup(@RequestParam("taskId") String tas, String id, HttpSession session) throws Exception {
        String taskId = tas;
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        UserInfo userInfo = (UserInfo) session.getAttribute(SystemEnum.SESSION_USER.getValue());
        String userId = userInfo.getUserId().toString();
        String userName = "";
        if (id != null & !id.equals("0")) {
            List<Task> list = taskService.createTaskQuery().taskId(taskId).list();
            Task task1 = list.get(0);
            System.out.println("流程实例ID" + task1.getProcessDefinitionId());
            FormList formlist = formListService.findByProcessInstanceId(task1.getProcessDefinitionId());
            System.out.println("根据流程实例Id获取cTableName" + formlist.getCTableName());
            String cTableName = formlist.getCTableName();
            Map<String, String> map = new HashMap<>();
            System.out.println(task1.getId());

            map.put(cTableName + "_id", id);
            String sql1 = sqlData.findByprocessInstanceId(cTableName, map);
            System.out.println(sql1);
            List<Map<String, Object>> maps1 = jdbcTemplate.queryForList(sql1);
            com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(maps1));
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            userName = jsonObject.getString(cTableName + "_single_person");
        }

        /*try {*/

        System.out.println("传入的参数" + taskId);
        JSONObject json = new JSONObject();
        Map<String, Object> variables = new HashMap<String, Object>();
        //ProcessDefinitionEntity processDefinitionEntity = null;
        ProcessDefinitionEntity processDefinitionEntity = null;

        String id1 = null;

        TaskDefinition task = null;

        //获取流程实例Id信息
        Task tasks = taskService.createTaskQuery().taskId(taskId).singleResult();
        System.out.println(tasks.getExecutionId());
        System.out.println(tasks.getProcessInstanceId());
        // ProcessInstance pi = runtimeService.startProcessInstanceById(ProcessInstanceId,variables);
        String processInstanceId = tasks.getProcessInstanceId();
        //获取流程发布Id信息
        String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();

        processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(definitionId);

        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();

        //当前流程节点Id信息
        String activitiId = execution.getActivityId();

        //获取流程所有节点信息
        List<ActivityImpl> activitiList = processDefinitionEntity.getActivities();
        System.out.println(activitiList);
        //遍历所有节点信息
        String Assignee = "";
        String Assignee2="";
        for (ActivityImpl activityImpl : activitiList) {
            id1 = activityImpl.getId();

            // 找到当前节点信息
            if (activitiId.equals(id1)) {
                //获取下一个节点信息
                task = nextTaskDefinition(activityImpl, activityImpl.getId(), null, processInstanceId);

                if (task != null) {
                    if (userName != null && !userName.equals("")) {
                        if (task.getAssigneeExpression().getExpressionText().equals("提交部门负责人")) {
                            Assignee = findDepartmentHead(userName);
                        } else if (task.getAssigneeExpression().getExpressionText().equals("提交人部门分管领导")) {
                            Assignee = findDepartmentalLeadership(userName);
                        }else if(task.getAssigneeExpression().getExpressionText().equals("中心主任")){
                            Assignee = findDirector(userName);
                        }
                        break;
                    }

                }

            }
        }

        if (task == null) {
            System.out.println("最后的节点；");
        } else {
            if (task.getAssigneeExpression().getExpressionText() == null || "".equals(task.getAssigneeExpression().getExpressionText())) {

            } else {
                if (Assignee != null && !("").equals(Assignee)) {
                    JdbcTemplate jdbcTemplate1 = new MSFactory().getJdbcTemplate();
                    String sql2 = "select personnelId from user_info where userId =" + Integer.parseInt(Assignee);
                    List<Map<String, Object>> maps1 = jdbcTemplate1.queryForList(sql2);
                    com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(maps1));
                    JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                    int personnelId = jsonObject2.getIntValue("personnelId");
                    String sql = "select * from PersonnelFiles where PersonnelFiles_id = " + personnelId;
                    json.put("assignee", jdbcTemplate.queryForList(sql));
                }else{
                    UserInfo byPersonnelId = userInfoService.findByPersonnelId(Integer.parseInt(task.getAssigneeExpression().getExpressionText()));
                    String sql = "select * from PersonnelFiles where PersonnelFiles_id = " + byPersonnelId.getPersonnelId();
                    json.put("assignee", jdbcTemplate.queryForList(sql));
                }

            }
				        	/*}else {
				        		json.put("assignee", "");
				        		System.out.println("未查询到人员信息");
				        	}*/
				        	/*if(task.getCandidateUserIdExpressions() !=null && !"".equals(task.getCandidateUserIdExpressions())) {
				        		String[] sbs = task.getCandidateUserIdExpressions().toString().split(",");
				        		String sql = "";
				        		for (int l = 0; l < sbs.length; l++) {
									String userId = sbs[l];
									sql += "" ;
									System.out.println(sbs[l]);
									}
				        		String candidateSql = "";*/
            json.put("candidateUserId", "");
				        	/*}else {
				        		json.put("candidateUserId", "");
				        		System.out.println("未查询到候选人信息");
				        	}*/
				        	/*if(task.getCandidateGroupIdExpressions() !=null && !"".equals(task.getCandidateGroupIdExpressions())) {
				        		String[] sbs = task.getCandidateGroupIdExpressions().toString().split(",");
				        		String sql = "";
				        		for (int l = 0; l < sbs.length; l++) {
									String userId = sbs[l];
									sql += "" ;
									System.out.println(sbs[l]);
									}
				        		String candidateSql = "";*/
            json.put("candidateGroupId", "");
				        	/*}else {
				        		json.put("candidateGroupId", "");
				        		System.out.println("未查询到候选组信息");
				        	}*/
            //json.put("assignee", task.getAssigneeExpression());
            //json.put("candidateUserId", task.getCandidateUserIdExpressions());
            //json.put("candidateGroupId", task.getCandidateGroupIdExpressions());
            System.out.println(json.toJSONString());
        }
        return json.toString();
				    /*	} catch (Exception e) {
							 json.put("msg", "异常");
							 return json.toString();
						} */
    }

    /**
     * 下一个任务节点信息,
     * <p>
     * 如果下一个节点为用户任务则直接返回,
     * <p>
     * 如果下一个节点为排他网关, 获取排他网关Id信息, 根据排他网关Id信息和execution获取流程实例排他网关Id为key的变量值,
     * 根据变量值分别执行排他网关后线路中的el表达式, 并找到el表达式通过的线路后的用户任务信息
     *
     * @param  activityImpl     流程节点信息
     * @param       activityId             当前流程节点Id信息
     * @param       elString               排他网关顺序流线段判断条件, 例如排他网关顺序留线段判断条件为${money>1000}, 若满足流程启动时设置variables中的money>1000, 则流程流向该顺序流信息
     * @param       processInstanceId      流程实例Id信息
     * @return
     */
    private TaskDefinition nextTaskDefinition(ActivityImpl activityImpl, String activityId, String elString, String processInstanceId) {

        PvmActivity ac = null;

        Object s = null;

        //如果遍历节点为用户任务并且节点不是当前节点信息
        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            //获取该节点下一个节点信息
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior()).getTaskDefinition();
            return taskDefinition;
//            return null;
        } else {
            //获取节点所有流向线路信息
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;
            for (PvmTransition tr : outTransitions) {
                ac = tr.getDestination(); //获取线路的终点节点
                //如果流向线路为排他网关
                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    //如果网关路线判断条件为空信息
                    if (StringUtils.isEmpty(elString)) {
                        //获取流程启动时设置的网关判断条件信息
                        elString = getGatewayCondition(ac.getId(), processInstanceId);
                    }
                    //如果排他网关只有一条线路信息
                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString, processInstanceId);
                    } else if (outTransitionsTemp.size() > 1) {  //如果排他网关有多条线路信息
                        for (PvmTransition tr1 : outTransitionsTemp) {
                            s = tr1.getProperty("conditionText");  //获取排他网关线路判断条件信息
                            //判断el表达式是否成立
                            if (isCondition(ac.getId(), StringUtils.trim(s.toString()), elString,processInstanceId)) {
                                return nextTaskDefinition((ActivityImpl) tr1.getDestination(), activityId, elString, processInstanceId);
                            }
                        }
                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {
                    // return ((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition();
                    if (StringUtils.isEmpty(elString)) {
                        //获取流程启动时设置的网关判断条件信息
                        elString = getGatewayCondition(ac.getId(), processInstanceId);
                    }
                    s = tr.getProperty("conditionText");
                    if(s!=null&&!s.equals("")) {
                        if (isCondition(ac.getId(), StringUtils.trim(s.toString()), elString, processInstanceId)) {
                            return nextTaskDefinition((ActivityImpl) tr.getDestination(), activityId, elString, processInstanceId);
                        }
                    }else {
                        return ((UserTaskActivityBehavior)((ActivityImpl)ac).getActivityBehavior()).getTaskDefinition();
                    }
                } else {
                }
            }
            return null;
        }
    }

    /**
     * 查询流程启动时设置排他网关判断条件信息
     *
     * param String gatewayId          排他网关Id信息, 流程启动时设置网关路线判断条件key为网关Id信息
     * param String processInstanceId  流程实例Id信息
     * @return
     */
    public String getGatewayCondition(String gatewayId, String processInstanceId) {
        Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).singleResult();
        Object object = runtimeService.getVariable(execution.getId(), gatewayId);
        return object == null ? "": object.toString();
        //    return runtimeService.getVariable(execution.getId(), gatewayId).toString();
    }

    /**
     * 根据key和value判断el表达式是否通过信息
     *
     * param String key    el表达式key信息
     * param String el     el表达式信息
     * param String value  el表达式传入值信息
     * @return
     */
    public boolean isCondition(String key, String el, String value,String processInstanceId){
        ExpressionFactory factory = new ExpressionFactoryImpl();
        SimpleContext context = new SimpleContext();
//        String a = "[':;'\\[\\].]";
//        String aa = "";
//        Pattern p = Pattern.compile(a);
//        Matcher matcher = p.matcher(el);
//        String trim = matcher.replaceAll(aa).trim();
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        Map<String, Object> variables = taskService.getVariables(task.getId());
        for (String s : variables.keySet()){
            //获取流程变量用作于表达式的判断
            Object vData = variables.get(s);
            if( vData==null ||StringUtils.isEmpty(vData.toString())){
                vData = "";
            }
            context.setVariable(s, factory.createValueExpression(vData, vData.getClass()));
            System.out.println("aaa");
        }
        ValueExpression e = factory.createValueExpression(context, el, boolean.class);
        return (Boolean) e.getValue(context);
    }
    //=====================================================================获取下一节点信息======================================================//


    //===================================================================================驳回上一步======================================//

    /**
     * 驳回至上一步操作
     * 2019-04-18 0：44
     *
     * param taskId     当前任务ID     ID_
     * param activityId 目标节点任务ID  TASK_DEF_KEY_
     * @param variables  流程变量
     * @throws Exception
     */
    @RequestMapping(value = "/backupgroud.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public void backupgroud(HttpSession session, @RequestParam("taskId") String taskId, Map<String, Object> variables, @RequestParam("fromId") String fromId) throws Exception {
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        JdbcTemplate jdbcTemplate1 = new MSFactory().getJdbcTemplate();
        UserInfo userInfo = (UserInfo) session.getAttribute(SystemEnum.SESSION_USER.getValue());
        String userId = userInfo.getUserId().toString();
        String userName = "";

        if (fromId != null & !fromId.equals("undefined")) {
            List<Task> list = taskService.createTaskQuery().taskAssignee(userId).list();
            Task task1 = list.get(0);
            System.out.println("流程实例ID" + task1.getProcessDefinitionId());
            FormList formlist = formListService.findByProcessInstanceId(task1.getProcessDefinitionId());
            //FormList formlist = formListService.findById(Integer.parseInt(t.getFormKey()));
            System.out.println("根据流程实例Id获取cTableName" + formlist.getCTableName());
            String cTableName = formlist.getCTableName();
            Map<String, String> map = new HashMap<>();
            System.out.println(task1.getId());
            map.put(cTableName + "_id", fromId);
            String sql1 = sqlData.findByprocessInstanceId(cTableName, map);
            System.out.println(sql1);
            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql1);
            com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(maps));
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            userName = jsonObject.getString(cTableName + "_single_person");
        }

        // 当前节点
        ActivityImpl currActivity = findActivitiImpl(taskId, null);
        System.out.println("=========" + currActivity);
        // 清空当前流向
        List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);
        // 创建新流向
        TransitionImpl newTransition = currActivity.createOutgoingTransition();
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        String processDefinitionId = task.getProcessDefinitionId();
        System.out.println(task.getTaskDefinitionKey());
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processDefinitionId);
        List<ActivityImpl> activities = processDefinitionEntity.getActivities();
        FormList formlist = formListService.findByProcessInstanceId(processDefinitionId);
        String cTableName = formlist.getCTableName();
        String activityId="";
        for (int i= 0 ;i<activities.size();i++){
            if(task.getTaskDefinitionKey().equals(activities.get(0).getId())){
                if(("StandbyFundReturn").equals(cTableName)||(("StandbyFundReturn"))==cTableName){
                    String sql2 = "select * from StandbyListDetails where StandbyFundReturn_id =" + fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql2);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int j = 0; j < jsonArray1.size(); j++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                        BigDecimal standbyListDetails_xgry_0008 = (BigDecimal)jsonObject1.get("StandbyListDetails_xgry_0008"); // 本次归还金额
                        String standbyListDetails_xgry_0001 = (String) jsonObject1.get("StandbyListDetails_xgry_0001");

                        String sql3 = "select * from ApplicationFund where ApplicationFund_code = '" + standbyListDetails_xgry_0001 + "'";
                        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql3);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                        JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                        BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额
                        BigDecimal applicationFund_xgry_0015 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0015"); // 剩余可用金额

                        // 已冻结金额 = 已冻结金额 - 本次冲抵金额
                        applicationFund_xgry_0017 = applicationFund_xgry_0017.subtract(standbyListDetails_xgry_0008);
                        // 终审单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                        applicationFund_xgry_0015 = applicationFund_xgry_0015.add(standbyListDetails_xgry_0008);
                        String sql4 = "update ApplicationFund set ApplicationFund_xgry_0017 =" + applicationFund_xgry_0017 + ",ApplicationFund_xgry_0015 = " + applicationFund_xgry_0015 + " where ApplicationFund_code =" + standbyListDetails_xgry_0001;
                        jdbcTemplate.update(sql4);
                    }
                }
                else if(("TransactionFundReturn").equals(cTableName)||("TransactionFundReturn")==cTableName) { // 归还金额驳回后更新金额
                    String sql2 = "select * from TransactionFundDetails where TransactionFundReturn_id =" + fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql2);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int j = 0; j < jsonArray1.size(); j++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                        BigDecimal transactionFundDetails_xgry_0007 = (BigDecimal)jsonObject1.get("TransactionFundDetails_xgry_0007"); // 本次归还金额
                        String transactionFundDetails_xgry_0001 = (String) jsonObject1.get("TransactionFundDetails_xgry_0001");

                        String sql3 = "select * from TransactionFundReturn where TransactionFundReturn_code = '" + transactionFundDetails_xgry_0001 + "'";
                        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql3);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                        JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                        BigDecimal transactionFund_xgry_0015 = (BigDecimal) jsonObject2.get("TransactionFund_xgry_0015"); // 已冻结金额
                        BigDecimal transactionFund_xgry_0013 = (BigDecimal) jsonObject2.get("TransactionFund_xgry_0013"); // 剩余可用金额

                        // 已冻结金额 = 已冻结金额 - 本次冲抵金额
                        transactionFund_xgry_0015 = transactionFund_xgry_0015.subtract(transactionFundDetails_xgry_0007);
                        // 终审单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                        transactionFund_xgry_0013 = transactionFund_xgry_0013.add(transactionFundDetails_xgry_0007);
                        String sql4 = "update ApplicationFund set TransactionFund_xgry_0015 =" + transactionFund_xgry_0015 + ",TransactionFund_xgry_0013 = " + transactionFund_xgry_0013 + " where ApplicationFund_code =" + transactionFundDetails_xgry_0001;
                        jdbcTemplate.update(sql4);
                    }
                }
                else if (("ExpensesReimbursement").equals(cTableName)||("ExpensesReimbursement")==cTableName) { // 日常费用报销
                    String sql1 = "select * from DetailsOffsetReserveGoods where ExpensesReimbursement_id =" + fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int j = 0; j < jsonArray1.size(); j++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                        BigDecimal DetailsOffsetReserveGoods_xgry_0008 = (BigDecimal)jsonObject1.get("DetailsOffsetReserveGoods_xgry_0008"); // 本次冲抵金额
                        String DetailsOffsetReserveGoods_xgry_0001 = (String) jsonObject1.get("DetailsOffsetReserveGoods_xgry_0001"); // 终审单据编号

                        String sql2 = "select * from ApplicationFund where ApplicationFund_code = '" + DetailsOffsetReserveGoods_xgry_0001 + "'";
                        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                        JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                        BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额
                        BigDecimal applicationFund_xgry_0015 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0015"); // 剩余可用金额

                        // 已冻结金额 = 已冻结金额 - 本次冲抵金额
                        applicationFund_xgry_0017 = applicationFund_xgry_0017.subtract(DetailsOffsetReserveGoods_xgry_0008);
                        // 终审单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                        applicationFund_xgry_0015 = applicationFund_xgry_0015.add(DetailsOffsetReserveGoods_xgry_0008);
                        String sql3 = "update ApplicationFund set ApplicationFund_xgry_0017 =" + applicationFund_xgry_0017 + ",ApplicationFund_xgry_0015 = " + applicationFund_xgry_0015 + " where ApplicationFund_code =" + DetailsOffsetReserveGoods_xgry_0001;
                        jdbcTemplate.update(sql3);
                    }
                } else if (("TravelExpense").equals(cTableName)||("TravelExpense")==cTableName) { // 差旅费报销
                    String sql1 = "select * from DetailsOfReserveFund where DetailsOfReserveFund_id =" + fromId;
                    List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
                    com.alibaba.fastjson.JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(list1));
                    for (int j = 0; j < jsonArray1.size(); j++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
                        BigDecimal detailsOfReserveFund_xgry_0008 = (BigDecimal)jsonObject1.get("DetailsOfReserveFund_xgry_0008"); // 本次冲抵金额
                        String detailsOfReserveFund_xgry_0001 = jsonObject1.getString("DetailsOfReserveFund_xgry_0001"); // 终审单据编号

                        String sql2 = "select * from ApplicationFund where ApplicationFund_code = '" + detailsOfReserveFund_xgry_0001 + "'";
                        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
                        com.alibaba.fastjson.JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(list2));
                        JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
                        BigDecimal applicationFund_xgry_0017 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0017"); // 已冻结金额
                        BigDecimal applicationFund_xgry_0015 = (BigDecimal) jsonObject2.get("ApplicationFund_xgry_0015"); // 剩余可用金额

                        // sum1 终身单据剩余可用金额 = 终审单据剩余可用金额 + 本次冲抵金额
                        BigDecimal sum1 = applicationFund_xgry_0015.add(detailsOfReserveFund_xgry_0008);
                        // sum2 已冻结金额 = 终审单据已冻结金额 - 本次冲抵金额
                        BigDecimal sum2 = applicationFund_xgry_0017.subtract(detailsOfReserveFund_xgry_0008);

                        String sql3 = "update ApplicationFund set ApplicationFund_xgry_0015 =" + sum1 + ",ApplicationFund_xgry_0017 = " + sum2 + "  where ApplicationFund_code =" + detailsOfReserveFund_xgry_0001;
                        jdbcTemplate.update(sql3);
                    }
                }
                activityId="end";
                break;
            }else if(activities.get(i).getId().equals(task.getTaskDefinitionKey())){
                activityId = activities.get(i-1).getId();
                ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinitionEntity).findActivity(activityId);
                if ("exclusiveGateway".equals(activityImpl.getProperty("type"))){
                    activityId = activities.get(i-2).getId();
                }
                break;
            }
        }

        System.out.println("-------------" + activityId);
        // 目标节点
        ActivityImpl pointActivity = findActivitiImpl(taskId, activityId);
        String executionId = task.getExecutionId();
        // 设置新流向的目标节点
        newTransition.setDestination(pointActivity);
        // 执行转向任务
        taskService.complete(taskId, variables);
        // 删除目标节点新流入
        pointActivity.getIncomingTransitions().remove(newTransition);
        // 还原以前流向
        restoreTransition(currActivity, oriPvmTransitionList);
        String Assignee = "";
        List<Task> list1 = taskService.createTaskQuery().processDefinitionId(processDefinitionId).list();
        if (list1.size() > 0) {
            Task task1 = list1.get(0);
            if (task1 != null) {
                if (userName != null && !userName.equals("undefined")&& !userName.equals("")) {
                    if (task1.getAssignee().equals("提交部门负责人")) {
                        Assignee = findDepartmentHead(userName);
                    } else if (task1.getAssignee().equals("提交人部门分管领导")) {
                        Assignee = findDepartmentalLeadership(userName);
                    }else if(task1.getAssignee().equals("中心主任")){
                        Assignee = findDirector(userName);
                    }
                    if(!Assignee.equals("")){
                        taskService.setAssignee(task1.getId(), Assignee);
                    }else{
                        UserInfo byPersonnelId = userInfoService.findByPersonnelId(Integer.parseInt(task1.getAssignee()));
                        taskService.setAssignee(task1.getId(),byPersonnelId.getUserId()+"");
                    }
                }
            }
        }


        if (activityId.equals("end")) {
            String sql = "update " + cTableName + " set " + cTableName + "_state =" + 0 + " where " + cTableName + "_id " + "=" + fromId;
            int update = jdbcTemplate.update(sql);
        } else {
            String sql = "update " + cTableName + " set " + cTableName + "_state =" + 4 + " where " + cTableName + "_id " + "=" + fromId;
            int update = jdbcTemplate.update(sql);
        }
        System.out.println("单据被驳回");
    }

//===================================================================================驳回上一步======================================//

    /**
     * 流程部门负责人功能
     *
     * param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findDepartmentHead.do", produces = "application/json;charset=utf-8")
    public String findDepartmentHead(String userName) throws Exception {
        String departmentalManagement_departmentsHead = reviewerService.findDepartmentHead(userName);
        System.out.println(departmentalManagement_departmentsHead);
        return departmentalManagement_departmentsHead;
    }

    /**
     * 流程部门分管领导功能
     *
     * param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findDepartmentalLeadership.do", produces = "application/json;charset=utf-8")
    public String findDepartmentalLeadership(String userName) throws Exception {
        String DepartmentalManagement_DepartmentalLeadership = reviewerService.findDepartmentalLeadership(userName);
        return DepartmentalManagement_DepartmentalLeadership;
    }

    /**
     * 提交中心主任
     */
    @RequestMapping(value = "/findDirector.do", produces = "application/json;charset=utf-8")
    public String findDirector(String username) throws Exception {
        String director = reviewerService.findDirector(username);
        System.out.println(director);
        return director;
    }






    /**
     * 根据单据id查询单据状态
     * param procinstId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findStateById.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String findState(String id,String cTableName) throws Exception {
        JSONObject json = new JSONObject();
        String sql = "select "+cTableName+"_state from "+cTableName+" where "+cTableName+"_id = " +id ;
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        json.put("state", jdbcTemplate.queryForList(sql));
        return json.toJSONString();
    }
    /**
     * 查询单据是否是办理中
     * @Param userId
     */
    public TaskQuery createTodoTaskQuery(String userId){
        TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(userId);
        return  taskQuery;
    }
    /***
     * 查询单据目前审核状态
     * @Param fromId
     */
    @RequestMapping(value = "/StatusQuery.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String StatusQuery(String cTableName,String formId) throws Exception {
        JSONObject json = new JSONObject();
        String sql = "select "+cTableName+"_processInstanceId from "+cTableName+" where "+cTableName+"_id =" +formId;
        //   System.out.println("sql==========="+sql);
        JdbcTemplate jdbcTemplate = dbServer.getJdbcTemplate(2);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(maps));
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        String processInstanceId = jsonObject.getString(cTableName+"_processInstanceId");
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        List<Comment> commentList = taskService
                .getProcessInstanceComments(processInstanceId);
        // 改变顺序，按原顺序的反向顺序返回list
        Collections.reverse(commentList); //集合元素反转
        json.put("postil", commentList);//流程历史批注
        json.put("processInstanceId",processInstanceId);
        System.out.println(json.toJSONString());
        return json.toJSONString();
    }

    /**
     * 在办理任务时查询是否有修改权限
     */
    @RequestMapping(value = "/findControlByProcessInstanceId.do",method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String findControlByProcessInstanceId(String processInstanceId){
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        String taskDefinitionKey = task.getTaskDefinitionKey();
        FormControl byTaskId = formControlService.findByTaskId(taskDefinitionKey);
        JSONObject json = new JSONObject();
        if (byTaskId!=null){
            json.put("state",byTaskId.getEditAuthority());
        }else {
            json.put("state",0);
        }
        return json.toString();
    }
}
